package com.bite.book.controller;

import com.bite.book.constant.Constants;
import com.bite.book.model.UserInfo;
import com.bite.book.service.UserInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserInfoService userInfoService;

    /**
     *
     * @param name
     * @param password
     * @param session
     * @return  true: 密码正确, false: 密码错误
     */
    @RequestMapping("/login")
    public Boolean login(String name, String password, HttpSession session){
        log.info("用户登录, name:" + name);
        //1. 参数校验
        //2. 校验账号和密码是否正确
        //3. 设置session
        //4. 返回结果
        if (!StringUtils.hasLength(name) || !StringUtils.hasLength(password)){
            return false;
        }
        //根据用户名, 获取用户信息
        UserInfo userInfo = userInfoService.queryUserInfoByName(name);
        if (userInfo==null){
            return false;
        }
        if (password.equals(userInfo.getPassword())) {
            userInfo.setPassword("");
            session.setAttribute(Constants.SESSION_USER_KEY, userInfo);
            return true;
        }
        //因为还未学习数据库相关操作, 暂且写死
//        if ("admin".equals(name) && "admin".equals(password)){
//            session.setAttribute("userName", name);
//            return true;
//        }

        return false;
    }
}
